﻿using AutoMapper;
using Serilog;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using WCS_Entity.Dto.RcsDto;
using WCS_Entity.Dto.UpperSysDto;
using WCS_Entity.Entity.UpperSys;
using WCS_Entity.Rcs;
using WCS_Repository.Interface;
using WCS_Repository.Repositories;
using WCS_Service.Interface;

namespace WCS_Service.Services
{
    /// <summary>
    /// 上位系统APi接口配置服务
    /// </summary>
    public class UpperSysApiService : BaseService<UpperSysServiceApiEntity>, IUpperSysApiService
    {
        private readonly IUpperSysServiceApiRepository _upperSysServiceApiRepository;
        private readonly IMapper _mapper;

        public UpperSysApiService(IMapper mapper, IUpperSysServiceApiRepository upperSysServiceApiRepository) 
        {
            _upperSysServiceApiRepository = upperSysServiceApiRepository;
            _mapper = mapper;
        }

        public async Task<UpperSysServiceApiDto> CreateUppserSysApiAsync(CreatUpperSysServiceApiDto dto)
        {
            UpperSysServiceApiDto result = new UpperSysServiceApiDto();
            var flag = await _upperSysServiceApiRepository.ExistsAsync(r => r.apiName == dto.apiName);
            if (flag)
            {
                Log.Error($"创建上位服务的API{dto.apiName}已经存在");
                return null;
            }
            var entity = _mapper.Map<UpperSysServiceApiEntity>(dto);

            entity.createTime = DateTime.Now;

            await _upperSysServiceApiRepository.InsertAsync(entity);

            result = _mapper.Map<UpperSysServiceApiDto>(entity);
            return result;
        }

        public async Task<bool> DeleteUppserSysApi(int id)
        {
            return await _upperSysServiceApiRepository.DeleteByIdAsync(id);
        }

        public async Task<List<UpperSysServiceApiDto>> QueryAllUppserSysApiAsync()
        {
            List<UpperSysServiceApiDto> result = new List<UpperSysServiceApiDto>();
            Expression<Func<UpperSysServiceApiEntity, object>> orderEx = p => p.createTime;
            var entityInfos = await _upperSysServiceApiRepository.QueryPageAsync(null, orderEx, OrderByType.Desc, 1, 10);
            if (entityInfos is null || !entityInfos.Any())
            {
                Log.Error("查询所有上位服务API接口失败");
                return null;
            }
            List<Task<UpperSysServiceApiDto>> entityList = new List<Task<UpperSysServiceApiDto>>();
            foreach (var entityInfo in entityInfos)
            {
                entityList.Add(GetDtoInfoAsync(entityInfo));
            }
            await Task.WhenAll(entityList);
            result = entityList.Select(e => e.Result).ToList();
            return result;
        }

        public async Task<UpperSysServiceApiDto> QueryUppserSysApiAsync(int id)
        {
            UpperSysServiceApiDto result = new UpperSysServiceApiDto();

            var entityInfo = await _upperSysServiceApiRepository.QueryByIdAsync(id);
            if (entityInfo is null)
            {
                Log.Error($"查询指定上位服务API{id}失败");
                return null;
            }
            result = _mapper.Map<UpperSysServiceApiDto>(entityInfo);
            return result;
        }
        /// <summary>
        /// 根据上位服务ID查询所有API接口配置
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<List<UpperSysServiceApiDto>> QueryUppserSysApiBaseIdAsync(int id)
        {
            List<UpperSysServiceApiDto> result = new List<UpperSysServiceApiDto>();
            Expression<Func<UpperSysServiceApiEntity, bool>> expression = eq => eq.upperSysId == id;
            var entitys = await _upperSysServiceApiRepository.QueryListByClauseAsync(expression);
            if (entitys is null || !entitys.Any())
            {
                Log.Error($"查询上位服务:{id}的API信息不存在");
                return null;
            }
            List<Task<UpperSysServiceApiDto>> addInfos = new();
            foreach (var entity in entitys)
            {
                addInfos.Add(GetDtoInfoAsync(entity));
            }
            await Task.WhenAll(addInfos);
            result = addInfos.Select(e => e.Result).ToList();
            return result;
        }

        public async Task<UpperSysServiceApiDto> UpdateUppserSysApiAsync(UpdateUpperSysServiceApiDto dto)
        {
            UpperSysServiceApiDto result = new UpperSysServiceApiDto();
            var entityInfo = await _upperSysServiceApiRepository.QueryByIdAsync(dto.id);
            if (entityInfo is null)
            {
                Log.Error($"编辑上位服务API{dto.id}不存在");
                return null;
            }
            if (entityInfo.route != dto.route)
            {
                entityInfo.route = dto.route;
            }
            if (entityInfo.apiName != dto.apiName)
            {
                entityInfo.apiName = dto.apiName;
            }
            if (entityInfo.describe != dto.describe)
            {
                entityInfo.describe = dto.describe;
            } 
            if (entityInfo.WCSDomainName != dto.WCSDomainName)
            {
                entityInfo.WCSDomainName = dto.WCSDomainName;
            }
            if (entityInfo.type != dto.type)
            {
                entityInfo.type = dto.type;
            }
            if (entityInfo.Extend1 != dto.Extend1)
            {
                entityInfo.Extend1 = dto.Extend1;
            }
            if (entityInfo.Extend2 != dto.Extend2)
            {
                entityInfo.Extend2 = dto.Extend2;
            }
            if (entityInfo.Extend3 != dto.Extend3)
            {
                entityInfo.Extend3 = dto.Extend3;
            }
            if (entityInfo.Extend4 != dto.Extend4)
            {
                entityInfo.Extend4 = dto.Extend4;
            }
            if (entityInfo.Extend5 != dto.Extend5)
            {
                entityInfo.Extend5 = dto.Extend5;
            }

            entityInfo.updataTime = DateTime.Now;
            result = _mapper.Map<UpperSysServiceApiDto>(entityInfo);
            return result;
        }

        #region private 
        private async Task<UpperSysServiceApiDto> GetDtoInfoAsync(UpperSysServiceApiEntity entity)
        {
            return await Task.Run(() => _mapper.Map<UpperSysServiceApiDto>(entity));
        }
        #endregion
    }
}
